package com.zoffy.bi.manager;

import com.zoffy.bi.common.ErrorCode;
import com.zoffy.bi.exception.ThrowUtils;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
@Service
public class RedisLimiterManager {
    @Resource
    RedissonClient redissonClient;
    public void doRateLimit(String key){
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        rateLimiter.trySetRate(RateType.OVERALL, 2, 1, RateIntervalUnit.SECONDS);
        boolean res = rateLimiter.tryAcquire(1);
        ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR,"频繁访问");
    }
}
